package com.cogent.business.action.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.cogent.business.action.AbstractAction;
import com.cogent.business.cache.UserCacheManager;
import com.cogent.business.domain.UserDomain;
import com.cogent.business.domain.WebUserDomain;
import com.cogent.business.helper.UserDomainHelper;
import com.cogent.common.date.JodaDateUtil;
import com.cogent.common.util.FormUtil;
import com.cogent.common.util.Globals;
import com.cogent.common.util.MD5;
import com.cogent.common.util.MapUtil;
import com.cogent.common.util.StringUtil;
import com.cogent.dao.domain.QueryParamDomain;
import com.cogent.dao.type.QueryType;

public class LoginAction extends AbstractAction {
	
	public String logout() {
		Object userid = ServletActionContext.getRequest().getSession().getAttribute("userid");
		if(userid != null) {
			UserCacheManager.remove(userid.toString());
			ServletActionContext.getRequest().getSession().removeAttribute(userid.toString());
		}
		
		return "login";
	}
	
	public String login() {
		HashMap formMap = getFormMapNoUser();
		setResponseMsg("formmap", formMap);
		
		return "login";
	}
	public String showModPwd(){		 
		HashMap formMap = getFormMapNoUser();
		if(formMap!=null){
				setResponseMsg("formmap", formMap);
		}else{
			return "login";
		}
	   return "showModPwd";
		
	}
	
	public String savePwd(){
		HashMap formMap = getFormMap();
		UserDomain userDomain = UserDomainHelper.getUser(ServletActionContext.getRequest());
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("id", userDomain.getId())); 
		
		bussinessFacade.createConn();
		HashMap userMap = bussinessFacade.getByID("sys_user", queryList);
		MD5 md5 = new MD5();
		if (!md5.getMD5ofStr(MapUtil.getStringValue(formMap, "oldpassword"))
				.equals(MapUtil.getStringValue(userMap, "password"))) {
			setResponseMsg("errmsg", "旧密码不正确!");
			return "error";
		}
		String newPassword = md5.getMD5ofStr(MapUtil.getStringValue(formMap, "newpassword"));
		userMap.put("password", newPassword);
		bussinessFacade.saveOrUpdate("sys_user", userMap);
		setResponseMsg("succmeg","1");
		return "success";
	  
		
	}
	
	public String execute() {
		HashMap formMap = getFormMapNoUser();
		List queryList = new ArrayList();
		queryList.add(new QueryParamDomain("username", MapUtil.getStringValue(formMap, "username")));
		MD5 md5 = new MD5();
		queryList.add(new QueryParamDomain("password", md5.getMD5ofStr(MapUtil.getStringValue(formMap, "password"))));
		queryList.add(new QueryParamDomain("status", "0"));
		try{
			bussinessFacade.createConn();
			HashMap userMap = bussinessFacade.getOneRowByTable("admin", queryList);
			if(userMap.size() > 0) {
			userMap.put("logindate",JodaDateUtil.getCurDate());
			HttpServletRequest request = ServletActionContext.getRequest(); 
			userMap.put("loginip",request.getRemoteAddr());
			bussinessFacade.update("admin", userMap);
				
				UserDomain userdomain = new UserDomain();
				userdomain.setId(MapUtil.getStringValue(userMap, "id"));
				userdomain.setUsername(MapUtil.getStringValue(userMap, "username"));
//				userdomain.setRealname(MapUtil.getStringValue(userMap, "realname"));
//				userdomain.setOrganid(MapUtil.getStringValue(userMap, "organid"));
//				userdomain.setOrgancode(MapUtil.getStringValue(userMap, "organcode"));
//				userdomain.setProviceid(MapUtil.getStringValue(userMap, "proviceid"));
//				userdomain.setProvicecode(MapUtil.getStringValue(userMap, "provicecode"));
//				userdomain.setUsertype(MapUtil.getStringValue(userMap, "usertype"));
				HashMap userPermissionMap = new HashMap();
//				if(!MapUtil.isEmpty(userMap, "roles")) {
//					queryList = new ArrayList();
//					queryList.add(new QueryParamDomain("roleid", MapUtil.getStringValue(userMap, "roles"), QueryType.INARRAY));
//					List roleList = bussinessFacade.query("sys_rolepermission", queryList);
//					Iterator it = roleList.iterator();
//					while(it.hasNext()) {
//						HashMap curdatamap = (HashMap)it.next();
//						String resourcecode = MapUtil.getStringValue(curdatamap, "resourcecode");
//						if(userPermissionMap.containsKey(resourcecode)) {
//							int curnum = MapUtil.getIntValue(curdatamap, "permissioncode");
//							curnum = curnum | MapUtil.getIntValue(userPermissionMap, resourcecode);
//							userPermissionMap.put(resourcecode, "" + curnum);
//						} else
//							userPermissionMap.put(resourcecode, MapUtil.getStringValue(curdatamap, "permissioncode"));
//					}
//				}
//				userdomain.setUserPermissionMap(userPermissionMap);
				UserCacheManager.put(userdomain.getId(), userdomain);
				ServletActionContext.getRequest().getSession().setMaxInactiveInterval(StringUtil.toInt(Globals.getProperty("sessiontime"), 300000000));
				ServletActionContext.getRequest().getSession().setAttribute("userid", userdomain.getId());
				
				return "success";
			} else {
				setResponseMsg("formmap", formMap);
				setResponseMsg("errmsg", "用户名或密码不正确!");
				return "login";
			}
		}finally {
			bussinessFacade.closeConn();
		}
	}	

	public String weblogin() {
		HashMap formMap = FormUtil.getAjaxFormInfo(ServletActionContext.getRequest());
		HashMap retMap = new HashMap();
		if(MapUtil.isEmpty(formMap, "username")) {
			retMap.put("state", "0");
			retMap.put("errmsg", "用户名不能为空!");
		} else if(MapUtil.isEmpty(formMap, "cardno")) {
			retMap.put("state", "0");
			retMap.put("errmsg", "身份证号不能为空!");
		} else if(MapUtil.isEmpty(formMap, "password")) {
			retMap.put("state", "0");
			retMap.put("errmsg", "用户密码不能为空!");
		}
		if(retMap.size() == 0) {
			List queryList = new ArrayList();
			queryList.add(new QueryParamDomain("username", MapUtil.getStringValue(formMap, "username")));
			queryList.add(new QueryParamDomain("cardno", MapUtil.getStringValue(formMap, "cardno")));
			MD5 md5 = new MD5();
			queryList.add(new QueryParamDomain("password", md5.getMD5ofStr(MapUtil.getStringValue(formMap, "password"))));
			queryList.add(new QueryParamDomain("status", "0"));			
			HashMap userMap = bussinessFacade.getOneRowByTable("party_member", queryList);
			if(userMap.size() > 0) {
				WebUserDomain webuserdomain = new WebUserDomain();
				webuserdomain.setId(MapUtil.getStringValue(userMap, "id"));
				webuserdomain.setRealname(MapUtil.getStringValue(userMap, "realname"));
				webuserdomain.setUsername(MapUtil.getStringValue(userMap, "username"));
				webuserdomain.setMobile(MapUtil.getStringValue(userMap, "mobile"));
				webuserdomain.setAdminid(MapUtil.getStringValue(userMap, "adminid"));
				webuserdomain.setOrganid(MapUtil.getStringValue(userMap, "organid"));
				webuserdomain.setOrgancode(MapUtil.getStringValue(userMap, "organcode"));
				webuserdomain.setProvicecode(MapUtil.getStringValue(userMap, "provicecode"));
				webuserdomain.setProviceid(MapUtil.getStringValue(userMap, "proviceid"));
				webuserdomain.setScore(MapUtil.getDoubleValue(userMap, "score"));
				webuserdomain.setLogintime(JodaDateUtil.getCurSystemDate().getTime());
				UserCacheManager.put(webuserdomain.getId(), webuserdomain);
				ServletActionContext.getRequest().getSession().setMaxInactiveInterval(StringUtil.toInt(Globals.getProperty("sessiontime"), 1800));
				ServletActionContext.getRequest().getSession().setAttribute("webuserid", webuserdomain.getId());
				retMap.put("state", "1");
			} else {
	          retMap.put("state", "0");
	          retMap.put("errmsg", "用户名或密码不正确!");
			}			
		}
	    String message = MapUtil.mapToJsonStr(retMap);
	    responseMsg(message);

	    return null;
	}
	
	public String weblogout() {
		Object userid = ServletActionContext.getRequest().getSession().getAttribute("webuserid");
		if(userid != null) {
			UserCacheManager.remove(userid.toString());
			ServletActionContext.getRequest().getSession().removeAttribute(userid.toString());
		}
		setResponseUrl(new HashMap(), "Web_index.action");
		
		return null;
	}
	
	public String sso() {
		UserDomain userDomain = UserDomainHelper.getUser(ServletActionContext.getRequest());
		if(userDomain == null)
			return "login";
		else
			return "success";
	}
}
